<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>我的订单 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <style>
        body { padding: 24px; background: #f5f7fa; }
        .order-container { max-width: 1200px; margin: 0 auto; }
        .order-card { 
            margin-bottom: 20px; 
            border-radius: 8px; 
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        .order-card:hover { 
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        .order-header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            padding: 16px 20px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
        }
        .order-info { 
            display: flex; 
            flex-direction: column; 
            gap: 4px;
        }
        .order-number { 
            font-size: 16px; 
            font-weight: bold; 
        }
        .order-time { 
            font-size: 12px; 
            opacity: 0.9; 
        }
        .order-status { 
            display: flex; 
            align-items: center; 
            gap: 8px;
        }
        .status-badge { 
            padding: 6px 12px; 
            border-radius: 20px; 
            font-size: 12px; 
            font-weight: bold;
            border: 2px solid rgba(255,255,255,0.3);
        }
        .status-1 { background: rgba(255, 193, 7, 0.9); color: #856404; }
        .status-2 { background: rgba(23, 162, 184, 0.9); color: white; }
        .status-3 { background: rgba(220, 53, 69, 0.9); color: white; }
        .status-4 { background: rgba(40, 167, 69, 0.9); color: white; }
        .order-amount { 
            font-size: 20px; 
            font-weight: bold; 
            color: #ff6b6b;
        }
        .order-content { 
            padding: 20px; 
            background: white;
            border-radius: 0 0 8px 8px;
        }
        .order-details { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); 
            gap: 16px; 
            margin-bottom: 16px;
        }
        .detail-item { 
            display: flex; 
            flex-direction: column; 
            gap: 4px;
        }
        .detail-label { 
            font-size: 12px; 
            color: #666; 
            font-weight: 500;
        }
        .detail-value { 
            font-size: 14px; 
            color: #333; 
            font-weight: 500;
        }
        .order-actions { 
            display: flex; 
            gap: 12px; 
            justify-content: flex-end;
            padding-top: 16px;
            border-top: 1px solid #eee;
        }
        .empty-state { 
            text-align: center; 
            padding: 60px 20px; 
            color: #999;
        }
        .empty-state i { 
            font-size: 48px; 
            margin-bottom: 16px; 
            opacity: 0.5;
        }
        .page-header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            margin-bottom: 24px;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .page-title { 
            font-size: 24px; 
            font-weight: bold; 
            color: #333;
        }
        .order-summary { 
            display: flex; 
            gap: 24px; 
            color: #666;
        }
        .summary-item { 
            text-align: center;
        }
        .summary-number { 
            font-size: 20px; 
            font-weight: bold; 
            color: #667eea;
        }
        .summary-label { 
            font-size: 12px; 
            margin-top: 4px;
        }
        .detail-modal { 
            max-width: 600px; 
            margin: 0 auto;
        }
        /* 状态筛选下拉框样式 */
        .layui-form-item {
            display: flex;
            align-items: center;
        }
        .layui-form-item select {
            min-width: 120px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 8px 12px;
            background: #fff;
            color: #333;
        }
        .layui-form-item select:focus {
            border-color: #5FB878;
            outline: none;
        }
        .detail-modal .layui-card { 
            margin-bottom: 16px; 
            text-align: center;
        }
        .detail-modal .layui-card-header { 
            background: #f8f9fa; 
            font-weight: bold;
            text-align: center;
        }
        .detail-modal .layui-card-body {
            text-align: left;
        }
        .product-list { 
            margin-top: 16px;
        }
        .product-item { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            padding: 12px; 
            border-bottom: 1px solid #eee;
        }
        .product-item:last-child { 
            border-bottom: none; 
        }
        .product-info { 
            flex: 1;
        }
        .product-name { 
            font-weight: bold; 
            margin-bottom: 4px;
        }
        .product-meta { 
            font-size: 12px; 
            color: #666;
        }
        .product-total { 
            text-align: right; 
            font-weight: bold; 
            color: #ff6b6b;
        }
    </style>
</head>
<body>
    <div class="order-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div>
                <div class="page-title">我的订单</div>
                <div class="order-summary">
                    <div class="summary-item">
                        <div class="summary-number" id="totalOrders">0</div>
                        <div class="summary-label">总订单</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-number" id="pendingOrders">0</div>
                        <div class="summary-label">待支付</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-number" id="completedOrders">0</div>
                        <div class="summary-label">已完成</div>
                    </div>
                </div>
            </div>
            <div style="display: flex; align-items: center; gap: 16px;">
                <div class="layui-form-item" style="margin-bottom: 0;">
                    <label style="margin-right: 8px; color: #666;">状态筛选：</label>
                    <select id="statusFilter" lay-filter="statusFilter" lay-search>
                        <option value="">全部状态</option>
                        <option value="1">待支付</option>
                        <option value="2">已支付</option>
                        <option value="3">已取消</option>
                        <option value="4">已送达</option>
                    </select>
                </div>
                <button id="goToMarketBtn" class="layui-btn layui-btn-primary">
                    <i class="fa fa-shopping-cart"></i> 返回超市
                </button>
            </div>
        </div>

        <!-- 订单列表 -->
        <div id="orderList">
            <!-- 订单列表将通过JavaScript动态生成 -->
        </div>
    </div>

    <script src="../lib/layui-v2.6.3/layui.js"></script>
    <script>
        layui.use(['jquery', 'layer', 'form'], function () {
            var $ = layui.jquery;
            var layer = layui.layer;
            var form = layui.form;
            
            var allOrders = []; // 存储所有订单数据
            var currentStatusFilter = ''; // 当前状态筛选

            // 全局设置ajax请求头
            $.ajaxSetup({
                beforeSend: function(xhr) {
                    const data = JSON.parse(localStorage.getItem('user'));
                    //输出token
                    console.log(data.token);
                    if (data.token) {
                        xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                    }
                }
            });
            
            // 获取订单状态文本
            function getStatusText(status) {
                switch(status) {
                    case 1: return '待支付';
                    case 2: return '已支付';
                    case 3: return '已取消';
                    case 4: return '已送达';
                    default: return '未知状态';
                }
            }
            
            // 获取订单状态样式类
            function getStatusClass(status) {
                return 'status-' + status;
            }
            
            // 获取订单状态图标
            function getStatusIcon(status) {
                switch(status) {
                    case 1: return 'fa fa-clock-o';
                    case 2: return 'fa fa-credit-card';
                    case 3: return 'fa fa-times-circle';
                    case 4: return 'fa fa-check-circle';
                    default: return 'fa fa-question-circle';
                }
            }
            
            // 更新订单统计
            function updateOrderSummary() {
                var total = allOrders.length;
                var pending = allOrders.filter(order => order.status === 1).length;
                var completed = allOrders.filter(order => order.status === 4).length;
                
                $('#totalOrders').text(total);
                $('#pendingOrders').text(pending);
                $('#completedOrders').text(completed);
            }
            
            // 筛选订单
            function filterOrders() {
                var filteredOrders = allOrders;
                
                if (currentStatusFilter !== '' && currentStatusFilter !== null) {
                    filteredOrders = allOrders.filter(order => order.status == currentStatusFilter);
                }
                
                displayOrders(filteredOrders);
            }
            
            // 显示订单列表
            function displayOrders(orders) {
                var html = '';
                
                if (orders.length === 0) {
                    html = `
                        <div class="empty-state">
                            <i class="fa fa-shopping-bag"></i>
                            <div style="font-size: 18px; margin-bottom: 8px;">暂无订单记录</div>
                            <div>${currentStatusFilter !== '' ? '当前筛选条件下没有订单' : '您还没有下过订单，快去超市选购商品吧！'}</div>
                        </div>
                    `;
                } else {
                    orders.forEach(function(order) {
                        html += `
                            <div class="order-card layui-card">
                                <div class="order-header">
                                    <div class="order-info">
                                        <div class="order-number">订单号：${order.orderId}</div>
                                        <div class="order-time">${new Date(order.orderTime).toLocaleString()}</div>
                                    </div>
                                    <div class="order-status">
                                        <i class="${getStatusIcon(order.status)}"></i>
                                        <span class="status-badge ${getStatusClass(order.status)}">${getStatusText(order.status)}</span>
                                    </div>
                                    <div class="order-amount">¥${order.totalAmount}</div>
                                </div>
                                <div class="order-content">
                                    <div class="order-details">
                                        <div class="detail-item">
                                            <div class="detail-label">收货地址</div>
                                            <div class="detail-value">${order.deliveryAddress}</div>
                                        </div>
                                        <div class="detail-item">
                                            <div class="detail-label">联系电话</div>
                                            <div class="detail-value">${order.phoneNumber}</div>
                                        </div>
                                        <div class="detail-item">
                                            <div class="detail-label">备注信息</div>
                                            <div class="detail-value">${order.remark || '无'}</div>
                                        </div>
                                    </div>
                                    <div class="order-actions">
                                        <button class="layui-btn layui-btn-sm" onclick="showOrderDetail(${JSON.stringify(order).replace(/"/g, '&quot;')})">
                                            <i class="fa fa-eye"></i> 查看详情
                                        </button>
                                        ${order.status === 1 ? `
                                            <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="payOrderFromList(${order.orderId})">
                                                <i class="fa fa-credit-card"></i> 立即支付
                                            </button>
                                            <button class="layui-btn layui-btn-sm layui-btn-warm" onclick="cancelOrderFromList(${order.orderId})">
                                                <i class="fa fa-times"></i> 取消订单
                                            </button>
                                        ` : ''}
                                        ${order.status === 3 || order.status === 4 ? `
                                            <button class="layui-btn layui-btn-sm layui-btn-danger" onclick="deleteOrderFromList(${order.orderId})">
                                                <i class="fa fa-trash"></i> 删除订单
                                            </button>
                                        ` : ''}
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                }
                
                $('#orderList').html(html);
            }
            
            // 显示订单详情
            function showOrderDetail(order) {
                var html = `
                    <div class="detail-modal" style="text-align: center;">
                        <div class="layui-card">
                            <div class="layui-card-header">订单信息</div>
                            <div class="layui-card-body">
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; text-align: left;">
                                    <div><strong>订单号：</strong>${order.orderId}</div>
                                    <div><strong>下单时间：</strong>${new Date(order.orderTime).toLocaleString()}</div>
                                    <div><strong>订单状态：</strong><span class="status-badge ${getStatusClass(order.status)}">${getStatusText(order.status)}</span></div>
                                    <div><strong>总金额：</strong><span style="color: #ff6b6b; font-weight: bold;">¥${order.totalAmount}</span></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="layui-card">
                            <div class="layui-card-header">收货信息</div>
                            <div class="layui-card-body" style="text-align: left;">
                                <div><strong>收货地址：</strong>${order.deliveryAddress}</div>
                                <div><strong>联系电话：</strong>${order.phoneNumber}</div>
                                ${order.remark ? `<div><strong>备注：</strong>${order.remark}</div>` : ''}
                            </div>
                        </div>
                        
                        <div class="layui-card">
                            <div class="layui-card-header">商品清单</div>
                            <div class="layui-card-body">
                                <div class="product-list" id="productList_${order.orderId}">
                                    <div style="text-align: center; color: #999; padding: 20px;">加载中...</div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                var index = layer.open({
                    type: 1,
                    title: '订单详情',
                    area: ['700px', '600px'],
                    content: html,
                    shadeClose: true, // 点击弹窗外区域关闭
                    success: function() {
                        // 加载订单商品详情
                        loadOrderItems(order.orderId, index);
                    }
                });
            }
            
            // 加载订单商品详情
            function loadOrderItems(orderId, layerIndex) {
                $.ajax({
                    url: '/order/items',
                    method: 'GET',
                    data: { orderId: orderId },
                    success: function(res) {
                        if (res.code === 0) {
                            var items = res.data || [];
                            var html = '';
                            
                            if (items.length === 0) {
                                html = '<div style="text-align: center; color: #999; padding: 20px;">暂无商品信息</div>';
                            } else {
                                // 获取商品名称
                                var productIds = items.map(item => item.productId);
                                $.ajax({
                                    url: '/product/list',
                                    method: 'GET',
                                    success: function(productRes) {
                                        if (productRes.code === 0) {
                                            var products = productRes.data || [];
                                            var productMap = {};
                                            products.forEach(function(product) {
                                                productMap[product.productId] = product;
                                            });
                                            
                                            items.forEach(function(item) {
                                                var product = productMap[item.productId] || {};
                                                html += `
                                                    <div class="product-item">
                                                        <div class="product-info">
                                                            <div class="product-name">${product.name || '商品ID: ' + item.productId}</div>
                                                            <div class="product-meta">数量: ${item.quantity} | 单价: ¥${item.price}</div>
                                                        </div>
                                                        <div class="product-total">¥${(item.price * item.quantity).toFixed(2)}</div>
                                                    </div>
                                                `;
                                            });
                                            
                                            $(`#productList_${orderId}`).html(html);
                                        } else {
                                            // 如果获取商品信息失败，显示基本信息
                                            items.forEach(function(item) {
                                                html += `
                                                    <div class="product-item">
                                                        <div class="product-info">
                                                            <div class="product-name">商品ID: ${item.productId}</div>
                                                            <div class="product-meta">数量: ${item.quantity} | 单价: ¥${item.price}</div>
                                                        </div>
                                                        <div class="product-total">¥${(item.price * item.quantity).toFixed(2)}</div>
                                                    </div>
                                                `;
                                            });
                                            $(`#productList_${orderId}`).html(html);
                                        }
                                    },
                                    error: function() {
                                        // 如果获取商品信息失败，显示基本信息
                                        items.forEach(function(item) {
                                            html += `
                                                <div class="product-item">
                                                    <div class="product-info">
                                                        <div class="product-name">商品ID: ${item.productId}</div>
                                                        <div class="product-meta">数量: ${item.quantity} | 单价: ¥${item.price}</div>
                                                    </div>
                                                    <div class="product-total">¥${(item.price * item.quantity).toFixed(2)}</div>
                                                </div>
                                            `;
                                        });
                                        $(`#productList_${orderId}`).html(html);
                                    }
                                });
                            }
                            
                            $(`#productList_${orderId}`).html(html);
                        } else {
                            $(`#productList_${orderId}`).html('<div style="text-align: center; color: #999; padding: 20px;">加载失败</div>');
                        }
                    },
                    error: function() {
                        $(`#productList_${orderId}`).html('<div style="text-align: center; color: #999; padding: 20px;">加载失败</div>');
                    }
                });
            }
            
            // 加载订单列表
            function loadOrders() {
                // 从localStorage获取用户信息
                var userStr = localStorage.getItem('user');
                if (!userStr) {
                    layer.msg('请先登录', {icon: 2});
                    // 清空订单列表并显示未登录提示
                    $('#orderList').html(`
                        <div class="empty-state">
                            <i class="fa fa-user-times"></i>
                            <div style="font-size: 18px; margin-bottom: 8px;">请先登录</div>
                            <div>登录后可查看您的订单记录</div>
                        </div>
                    `);
                    return;
                }

                var user = JSON.parse(userStr);
                var userId = user.user ? user.user.userId : user.userId;
                if (!userId) {
                    layer.msg('用户信息不完整，请重新登录', {icon: 2});
                    // 清空订单列表并显示信息不完整提示
                    $('#orderList').html(`
                        <div class="empty-state">
                            <i class="fa fa-user-times"></i>
                            <div style="font-size: 18px; margin-bottom: 8px;">用户信息不完整</div>
                            <div>请重新登录后再试</div>
                        </div>
                    `);
                    return;
                }

                $.ajax({
                    url: '/order/list',
                    method: 'GET',
                    data: { userId: userId },
                    success: function(res) {
                        if (res.code === 0) {
                            allOrders = res.data || [];
                            filterOrders(); // 使用筛选函数显示订单
                            updateOrderSummary();
                        } else {
                            layer.msg('获取订单失败：' + res.message, {icon: 2});
                            // 显示获取失败提示
                            $('#orderList').html(`
                                <div class="empty-state">
                                    <i class="fa fa-exclamation-triangle"></i>
                                    <div style="font-size: 18px; margin-bottom: 8px;">获取订单失败</div>
                                    <div>${res.message || '请稍后重试'}</div>
                                </div>
                            `);
                        }
                    },
                    error: function() {
                        layer.msg('获取订单失败，请稍后重试', {icon: 2});
                        $('#orderList').html(`
                            <div class="empty-state">
                                <i class="fa fa-exclamation-triangle"></i>
                                <div style="font-size: 18px; margin-bottom: 8px;">获取订单失败</div>
                                <div>请稍后重试</div>
                            </div>
                        `);
                    }
                });
            }
            
            // 从订单列表支付订单
            function payOrderFromList(orderId) {
                layer.confirm('确认支付此订单吗？', {
                    icon: 3,
                    title: '确认支付',
                    btn: ['确认支付', '取消']
                }, function(index) {
                    layer.close(index);
                    $.ajax({
                        url: '/order/pay',
                        method: 'POST',
                        data: { orderId: orderId },
                        success: function(res) {
                            if (res.code === 0) {
                                layer.msg('支付成功！', {icon: 1});
                                // 刷新订单列表
                                loadOrders();
                            } else {
                                layer.msg('支付失败：' + res.message, {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('支付失败，请稍后重试', {icon: 2});
                        }
                    });
                });
            }
            
            // 从订单列表取消订单
            function cancelOrderFromList(orderId) {
                layer.confirm('确认取消此订单吗？', {
                    icon: 3,
                    title: '确认取消',
                    btn: ['确认取消', '取消']
                }, function(index) {
                    layer.close(index);
                    $.ajax({
                        url: '/order/cancel',
                        method: 'POST',
                        data: { orderId: orderId },
                        success: function(res) {
                            if (res.code === 0) {
                                layer.msg('订单已取消', {icon: 1});
                                // 刷新订单列表
                                loadOrders();
                            } else {
                                layer.msg('取消失败：' + res.message, {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('取消失败，请稍后重试', {icon: 2});
                        }
                    });
                });
            }
            
            // 从订单列表删除订单
            function deleteOrderFromList(orderId) {
                layer.confirm('确认删除此订单吗？<br><br><span style="color: #ff6b6b; font-size: 12px;">删除后无法恢复，请谨慎操作！</span>', {
                    icon: 3,
                    title: '确认删除',
                    btn: ['确认删除', '取消']
                }, function(index) {
                    layer.close(index);
                    $.ajax({
                        url: '/order/delete',
                        method: 'POST',
                        data: { orderId: orderId },
                        success: function(res) {
                            if (res.code === 0) {
                                layer.msg('订单已删除', {icon: 1});
                                // 刷新订单列表
                                loadOrders();
                            } else {
                                layer.msg('删除失败：' + res.message, {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('删除失败，请稍后重试', {icon: 2});
                        }
                    });
                });
            }
            
            // 返回超市
            function goToMarket() {
                // 在主框架内打开超市页面
                if (typeof parent !== 'undefined' && parent.layui && parent.layui.miniTab) {
                    parent.layui.miniTab.openNewTabByIframe({
                        href: 'page/market.html',
                        title: '社区超市外卖'
                    });
                } else {
                    window.location.href = 'market.html';
                }
            }
            
            // 页面初始化
            $(function() {
                // 每次进入页面都重新加载订单数据
                loadOrders();
                
                // 延迟重新渲染表单，确保DOM完全加载
                setTimeout(function() {
                    form.render();
                    
                    // 监听状态筛选下拉框
                    form.on('select(statusFilter)', function(data) {
                        currentStatusFilter = data.value;
                        filterOrders();
                    });
                }, 100);
                
                // 绑定返回超市按钮事件
                $('#goToMarketBtn').on('click', function(e) {
                    e.preventDefault();
                    goToMarket();
                });
                
                // 备用的事件绑定方式 - 直接监听select变化
                $('#statusFilter').on('change', function() {
                    currentStatusFilter = $(this).val();
                    filterOrders();
                });
            });
            
            // 将函数暴露到全局作用域，供HTML中的onclick调用
            window.goToMarket = goToMarket;
            window.showOrderDetail = showOrderDetail;
            window.loadOrders = loadOrders;
            window.payOrderFromList = payOrderFromList;
            window.cancelOrderFromList = cancelOrderFromList;
            window.deleteOrderFromList = deleteOrderFromList;
        });
    </script>
</body>
</html> 